package com.cskaoyan.controller;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.User;
import com.cskaoyan.bean.address.WXAddress;
import com.cskaoyan.bean.address.WXAddressDetail;
import com.cskaoyan.bean.address.WXAddressSave;
import com.cskaoyan.bean.region.vo.RegionVo;
import com.cskaoyan.bean.region.wxvo.WxRegionVo;
import com.cskaoyan.service.RegionService;
import com.cskaoyan.service.WXAddressService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author: heliming
 * @date: 2021/6/7
 * @description:
 */



@RestController
@RequestMapping("wx")
public class WXAddressController {

    @Autowired
    WXAddressService wxAddressService;
    @Autowired
    RegionService regionService;

    @GetMapping("address/list")
    public BaseRespVo list() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer userId = user.getId();

        List<WXAddress> wxAddress = wxAddressService.selectAddressList(userId);

        return BaseRespVo.ok(wxAddress);

    }

    @GetMapping("address/detail")
    public BaseRespVo detail(Integer id) {
        WXAddressDetail wxAddressDetail = wxAddressService.selectAddressDetail(id);
        return BaseRespVo.ok(wxAddressDetail);
    }

    @PostMapping("address/save")
    public BaseRespVo save(@RequestBody WXAddressSave wxAddressSave) {
        //获取用户id
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer userId = user.getId();
        //修改
        if (wxAddressSave.getId() != 0) {
            if (wxAddressSave.getIsDefault()){
                wxAddressService.updateAddressDefaultFalse(wxAddressSave);
            }
            Integer id = wxAddressService.updateAddressDefault(wxAddressSave);
        } else {
            if (wxAddressSave.getIsDefault()){
                wxAddressService.updateAddressDefaultFalse(wxAddressSave);
            }
            //新增
            wxAddressService.insertAddressSave(wxAddressSave,userId);
        }
        return BaseRespVo.ok(wxAddressSave.getId());
    }

    @PostMapping("address/delete")
    public BaseRespVo delete(@RequestBody Map map) {
        Integer wxId = (Integer) map.get("id");
        wxAddressService.updateAddress(wxId);
        return BaseRespVo.ok();
    }


    @GetMapping("region/list")
    public BaseRespVo listRegion(Integer pid) {
        List<WxRegionVo> wxRegionVoList = regionService.selectRegionByPid(pid);
        return BaseRespVo.ok(wxRegionVoList);
    }

}
